package com.dayuanit.dy16.atm.interceptor;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy16.atm.dto.ResponseDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        Object userLogin = session.getAttribute("userLogin");
        if (userLogin != null) {
            return true;
        }

        String header = httpServletRequest.getHeader("X-Requested-With");
        if (StringUtils.isBlank(header)) {
            httpServletResponse.sendRedirect("/");
        } else {
            httpServletResponse.setContentType("application/json");
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            outputStream.write(JSON.toJSONString(ResponseDTO.unLogin()).getBytes("utf-8"));
            outputStream.flush();
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
